<template>
  <div class="app-container">
    <el-row v-if="tableData.length" type="flex" justify="center">
      <el-col :span="23">
        <el-container style="max-height: 810px; border: 1px solid #eee;border-radius: 10px;">
          <el-aside width="280px" style="border-right: 1px solid #eee;border-radius: 10px;">
            <el-input placeholder="搜索会话联系人" v-model="search" @input="filterMenu" clearable>
            </el-input>
            <el-menu :default-active="defaultActive" class="el-menu-vertical-demo" background-color="#2b324f"
              text-color="#fff">
              <template v-for="(item, i) in filteredItems">
                <el-menu-item :key="i" :index="item.UserId"
                  @click.native="clickGetUserChatRecordPages(item.Avatar, item.UserId, item.UserName)">
                  <div style="display: flex;justify-content: space-between;">
                    <div>
                      <el-avatar shape="square" :size="'medium'" :src="item.Avatar"
                        style="margin-right: 10px"></el-avatar>
                      <span style="margin-right: 4px; display: inline-block;
                      max-width: 8ch;
                      overflow: hidden;
                      white-space: nowrap;">{{ item.UserName }}</span>
                    </div>
                    <el-popover placement="top" width="150">
                      <div style="display: flex; justify-content: space-between; align-items: center; padding: 0 8px;">
                        <i class="el-icon-delete" style="font-size: 20px;color:#F56C6C;"></i>
                        <el-button type="danger" size="mini" @click="confirmDelete">删除</el-button>
                      </div>
                      <el-button slot="reference" type="text" icon="el-icon-delete"
                        @click.stop="handleDelete(item.UserId)"></el-button>
                    </el-popover>
                  </div>
                </el-menu-item>
              </template>
            </el-menu>
          </el-aside>
          <el-container>
            <el-header style="font-size: 20px">
              <div style="padding: 20px 5px; border-bottom: 1px solid #eee;">{{ nameha }}</div>
            </el-header>
            <el-main>
              <div class="card">
                <div v-if="isShow" class="card-body news-container" id="scrollContainer_Id" v-infinite-scroll="loadMore"
                  :infinite-scroll-disabled="loading" :infinite-scroll-distance="10" style="overflow:auto">
                  <div v-for="(o, i) in chartList.slice().reverse()" :key="i">
                    <!-- 角色1 -->
                    <el-row v-if="o.FromUser === nameha">
                      <el-col :span="12">
                        <div class="" style="display: flex;">
                          <div style="">
                            <el-avatar shape="square" :size="'medium'" :src="ava"
                              style="margin: 0 10px 10px 0;"></el-avatar>
                          </div>
                          <div class="">
                            <div v-if="o.ImageURL">
                              <div style="text-align: left;margin-bottom: 10px;">
                                <el-image
                                  style="max-width: 174px;max-height: 174px;border-radius: 4px;margin-bottom: 10px;"
                                  around :src="o.ImageURL" alt="图片" :fit="'fill'" :preview-src-list="previewSrcList">
                                </el-image>
                                <div style="color: #ccc;margin-top: 4px;font-size: 14px;">{{ o.SendTime | dateFormat }}
                                </div>
                              </div>
                            </div>
                            <div v-else class="textbox textboxbgc1">
                              <div>{{ o.Text }}</div>
                              <div style="color: #ccc;margin-top: 4px;">{{ o.SendTime | dateFormat }}</div>
                            </div>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                    <!-- 角色2 -->
                    <el-row v-else>
                      <el-col :span="12" :offset="12">
                        <div style="display: flex; justify-content: flex-end;">
                          <div>
                            <div v-if="o.ImageURL">
                              <div style="text-align: end;margin-bottom: 10px;">
                                <div>
                                  <el-image style="width: 174px;max-height: 174px; height: 100%; border-radius: 4px;"
                                    around :src="o.ImageURL" alt="图片" :fit="'contain'"
                                    :preview-src-list="previewSrcList">
                                  </el-image>
                                </div>
                                <div style="color: #ccc;margin-top: 4px;font-size: 14px;">{{ o.SendTime | dateFormat }}
                                </div>
                              </div>

                            </div>
                            <div v-else class="textbox textboxbgc">
                              <div> {{ o.Text }}</div>
                              <div style="color: #ccc;margin-top: 4px;">{{ o.SendTime | dateFormat }}</div>
                            </div>
                          </div>
                          <div style="text-align: end;">
                            <el-avatar shape="square" :size="'medium'" :src="routerAva"
                              style="margin: 0 0 10px 10px;"></el-avatar>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                  </div>

                  <div v-if="loading" class="no-more-text">加载中...</div>
                  <div v-if="noMore" class="no-more-text">没有更多了~</div>
                </div>
              </div>
            </el-main>
          </el-container>
        </el-container>
      </el-col>
    </el-row>
    <el-row v-else type="flex" justify="center">
      <el-col :span="16">
        <div style="max-height: 810px;border: 1px solid #eee;border-radius: 10px;">
          <el-empty description="暂无聊天记录"></el-empty>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import single from '@/views/record/single'
import group from '@/views/record/group'
import { DeleteC2cConv, GetUserConvListPages, GetUserChatRecordPagesByUserId } from '@/api/ChatRecord'
import { jsonToParams, jsonToFormData } from '@/utils'
import { getDateFormatYMDhms } from '@/utils/validate.js'
import { QueryBox, TipsBox } from '@/utils/feedback'


export default {
  name: 'ImUserRecords',
  components: { single, group },
  data() {
    return {
      search: '',
      srcList: [],
      activeName: 'single',
      dataSource: [],
      tableData: [],
      loading: false,
      total: 0,
      listQuery: {
        pageIndex: 1,
        pageSize: 15
      },
      chartList: [],
      nameha: '',
      ava: '',
      routerAva: '',
      previewSrcList: [],
      defaultActive: '',
      isdelete: false,
      deleteId: '',

      pageSize: 100,
      noMore: false,
      currentPage: 1,  // 当前页码
      isscroll: false,
      queryParams: {   // 请求参数
        // 根据实际需求添加参数，例如：
        fromUserId: '',
        toUserId: ''
      },
      isShow:true,
    }
  },
  watch: {
    $route: {
      handler(newVal) {
        console.log('new', newVal)
        if (newVal.name === 'ImUserRecords' && this.listQuery.fromUserId !== newVal.query.userId) {
          this.listQuery.fromUserId = newVal.query.userId
          this.routerAva = newVal.query.routerAva
          this.getDataList()
        }
      },
      deep: true
    },
  },
  computed: {
    filteredItems() {
      return this.tableData.filter(data => !this.search || data.UserName.includes(this.search));
    },
    disabled() {
      return this.loading || this.noMore
    },
  },
  filters: {
    dateFormat(time) {
      return getDateFormatYMDhms(time)
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    filterMenu() {
      // 这里可以添加额外的过滤逻辑，如果需要的话。例如，重置活动索引等。
      console.log('888')
    },
    handleDelete(id) {
      this.deleteId = id
    },
    confirmDelete() {
      const params = { fromUserId: this.$route.query.userId, toUserId: this.deleteId }
      QueryBox('是否删除与该联系人的聊天记录？').then(() => {
        DeleteC2cConv(jsonToParams(params)).then((res) => {
          if (res.statusCode === 200) {
            this.getDataList()
          }
        })
      })
    },
    handleClick(tab, event) {
      // console.log(tab, event)
    },
    getDataList() {
      const a = this.$route.query
      this.routerAva = a.routerAva
      this.listQuery.fromUserId = a.userId
      GetUserConvListPages(jsonToParams(this.listQuery)).then(res => {
        if (res.statusCode === 200) {
          if (res.data.DataList) {
            this.tableData = res.data.DataList
            this.total = res.data.RecordCount
            // 先点击一次
            this.clickGetUserChatRecordPages(this.tableData[0].Avatar, this.tableData[0].UserId, this.tableData[0].UserName)
          }
        }
      }).catch(() => {
        this.loading = false
      })
    },
    clickGetUserChatRecordPages(ava, id, name) {
      console.log('获取侧边栏后点击一次', '88888')
      this.isShow=false;
      this.$nextTick(() => {
              console.log('进来')
              let container2 = document.getElementById('scrollContainer_Id');
              container2.scrollTop = 0
            })
      this.ava = ava
      this.nameha = name
      this.defaultActive = id
      this.listQuery.fromUserId = this.$route.query.userId
      this.listQuery.toUserId = id

      // 初始加载第一页数据
      this.chartList = []
      this.queryParams.fromUserId = this.$route.query.userId
      this.queryParams.toUserId = id
      this.currentPage = 1
      this.noMore = false
      this.loadMore()
    },
    loadMore() {
      console.log('初始加载第一页数据', this.loading, this.noMore)
      if (this.loading || this.noMore) return
      this.loading = true
      const params = {
        ...this.queryParams,
        pageIndex: this.currentPage,
        pageSize: this.pageSize
      }
      this.getNew(params).then(() => {
        this.currentPage++
        this.loading = false
        this.isShow=true;
      }).catch(() => {
        this.loading = false
      })
    },
    getNew(params) {
      return GetUserChatRecordPagesByUserId(jsonToParams(params)).then(res => {
        console.log(res)
        if (res.statusCode === 200) {
          if (res.data.DataList) {
            const newData = res.data.DataList || []
            // 如果返回的数据为空或不足一页，则认为没有更多数据
            if (newData.length === 0 || newData.length < this.pageSize) {
              this.noMore = true
            }
            this.chartList = [...this.chartList, ...newData]
            this.$nextTick(() => {
              let container2 = document.getElementById('scrollContainer_Id');
              container2.addEventListener("scroll", this.handleScrollStart);
            })
          }
          this.previewSrcList = []
          this.chartList.forEach((item) => {
            if (item.ImageURL != null) {
              this.previewSrcList.push(item.ImageURL)
            }
          })
        }
      }).catch(error => {
        console.error('获取列表失败:', error)
        reject(error)
      })
    },
    handleScrollStart(event) {
      console.log("开始", event);
      // 在这里执行你的逻辑（如显示加载状态）
      const container = event.target;
      const currentScroll = container.scrollTop;
      // 防抖优化（200ms内只触发一次） 或许不用管上一次是拉倒哪里了，只要点击侧边栏，就设置=0
      if (currentScroll <= 2) { // 误差容忍值（防止抖动）
        this.handleScrollReset(container);
      }
    },
    // 回到原位时的回调
    handleScrollReset(container) {
      console.log("已回到原位", container);
      // 这里执行你的逻辑（如重置状态、加载初始数据等）
    },

  }
}
</script>

<style scoped>
.no-more-text {
  text-align: center;
  margin: 40px 0;
  color: #ccc;
  font-size: 14px;
}

.news-container {
  height: 800px;
  /* 设置固定高度 */
  overflow-y: scroll;
  /* 确保可以滚动 */

  /* 隐藏滚动条 - Chrome/Safari/Edge */
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE/Edge */
}

/* 隐藏滚动条 - Chrome/Safari */
.news-container::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}

.textbox {
  font-size: 14PX;
  border-radius: 4px;
  position: relative;
  margin-bottom: 10px;
  padding: 1rem;
}

.textboxbgc1 {
  background-color: rgba(185, 185, 185, 0.1);
}

.textboxbgc {
  background-color: #409EFF;
  color: #fff;

}

.textbox:hover {
  background-color: #eee;
  color: #333;
}

.textboxbgc:hover:after {
  border-left: 8px solid #eee;
}

.textboxbgc1:hover:after {
  border-right: 8px solid #eee;
}

.el-image-viewer__mask {
  background: #fff;
  opacity: 1;
  box-shadow: 0px 0px 1px 1px #ddd;
}

.textboxbgc1:after {
  content: "";
  position: absolute;
  top: 3px;
  left: -7px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid rgba(185, 185, 185, 0.1);
}

.textboxbgc:after {
  content: "";
  position: absolute;
  top: 3px;
  right: -7px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-left: 8px solid #409EFF;
}

::v-deep .el-image-viewer__wrapper {
  position: fixed;
  top: 10%;
  left: 25%;
  width: 960px;
  height: 720px;
}

::v-deep .el-menu-item.is-active {
  background-color: rgba(8, 8, 8, 0.2) !important;
  /* 自定义颜色 */
}

::v-deep .el-menu-item {
  padding: 0
}
</style>
